// components/workLogsItem/index.js
const api = require('../../utils/request.js')
const util = require('../../utils/util.js')
Component({
  options: {
    addGlobalClass: true
  },
  observers: {
    'timestamp': function (timestamp) {
      this.init()
    }
  },
  /**
   * 组件的属性列表
   */
  properties: {
    timestamp: {
      type: String,
      value: ''
    },
    worklog: {
      type: Object,
      value: null
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    imgHost: api.IMG_HOST,
    imgList: [],
    commentList: [],
    commentModalShow: false,
    commentText: ''
  },
  lifetimes: {
    attached () {
    }
  },
  /**
   * 组件的方法列表
   */
  methods: {
    sendComment({ detail }) {
      if (!detail.value) {
        wx.showToast({
          title: '请输入评论内容',
          icon: 'none'
        })
        return false
      }
      this.replyConstructionLog(detail.value).then(() => {
        const userInfo = wx.getStorageSync('userInfo')
        this.setData({
          commentModalShow: false,
          commentText: '',
          commentList: [
            ...this.data.commentList,
            {
              ConstructionLogReplyID: new Date().getTime(),
              ReplyerName: userInfo.NickName || `匿名用户${userInfo.ID}`,
              ReplyContent: detail.value
            }
          ]
        })
      })
    },
    replyConstructionLog(comment) {
      return new Promise(resolve => {
        api._post(`/User/Construction/Log/Reply?logID=${this.data.worklog.ID}&comment=${comment}`).then(res => {
          if (res.Code === 100000) {
            resolve(res.Data)
          }
        })
      })
    },
    showCommentModal() {
      this.setData({
        commentModalShow: true
      })
    },
    hideCommentModal() {
      this.setData({
        commentModalShow: false
      })
    },
    catchtapEvent() { },
    init () {
      if (this.data.worklog && this.data.worklog.Imgs) {
        const list = this.data.worklog.Imgs.split(',')
        let imgList = []
        list.map(item => {
          imgList.push(util.transformImgUrl(item, api.IMG_HOST))
        })
        this.setData({
          imgList: imgList
        })
        this.getCommentList().then(data => {
          this.setData({
            commentList: data
          })
        })
      }
    },
    getCommentList() {
      return new Promise(resolve => {
        api._get(`/User/Construction/Log/Reply/List`, {
          constructionLogID: this.data.worklog.ID
        }, {
          loading: false
        }).then(res => {
          if (res.Code === 100000) {
            resolve(res.Data)
          }
        })
      })
    },
    previewImage({ currentTarget }) {
      wx.previewImage({
        current: currentTarget.dataset.url,
        urls: this.data.imgList
      })
    }
  }
})
